import { createRouter, createWebHistory } from 'vue-router';
import axios from "@/utils/axios.ts";

// import Profile from '@/views/Profile.vue'; // 可选

const routes = [
    {/*初始页面*/
        path: '/',
        redirect: '/login' // 默认跳转到首页
    },
    // 在路由配置中添加 meta 字段来控制是否显示底部导航栏
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue'),
        meta: { showTabBar: false}
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/Register.vue'),
        meta: { showTabBar: false, requiresAuth: true }
    },
    {
        path: '/terms',
        name: 'Terms',
        component: () => import('@/views/Terms.vue'),
        meta: { showTabBar: false, requiresAuth: true }
    },
    {/*首页*/
        path: '/home',
        name: 'Home',
        component:() => import('@/views/Home.vue'),
        meta: {requiresAuth: true }
    },
    {/*关注*/
        path: '/following',
        name: 'Following',
        component:() => import('@/components/Following.vue'),
        meta: {requiresAuth: true }
    },
    {/*推荐*/
        path: '/recommend',
        name: 'Recommend',
        component:() => import('@/components/Recommend.vue'),
        meta: {requiresAuth: true }
    },
    {/*热点*/
        path: '/hotStop',
        name: 'HotStop',
        component:() => import('../views/HotStop.vue'),
        children:[
            {
                path: '',
                redirect: '/hotStop/all',//初始页面
            },
            {/*热点/全部*/
                path: 'all',// /hotStop/all
                name: 'HotStop-All',
                component:() => import('../views/HotStop-All.vue'),
                meta: {requiresAuth: true }
            },
            {/*热点/热榜*/
                path: 'topics',
                name: 'HotStop-Topics',
                component:() => import('../views/HotStop-Topics.vue'),
                meta: {requiresAuth: true }
            },
            {/*热点/游戏*/
                path: 'game1',
                name: 'HotStop-Game1',
                component:() => import('../views/HotStop-Game1.vue'),
                meta: {requiresAuth: true }
            },
            {/* 热点/游戏2 */
                path: 'game2',
                name: 'HotStop-Game2',
                component: () => import('../views/HotStop-Game2.vue'),
                meta: {requiresAuth: true }
            },
            {/* 热点/游戏3 */
                path: 'game3',
                name: 'HotStop-Game3',
                component: () => import('../views/HotStop-Game3.vue'),
                meta: {requiresAuth: true }
            },
        ]
    },
    {/* 帖子详细页 */
        path: '/postDetails/:postId',
        name: 'PostDetails',
        component: () => import('../views/PostDetails.vue'),
        meta: {requiresAuth: true },
        redirect: (to: any) => `/postDetails/${to.params.postId}/mainText`,
        children: [
            {
                path: 'mainText',
                name: 'PostDetails-MainText',
                component: () => import('../views/PostDetails-MainText.vue'),
                meta: {requiresAuth: true }
            },
            {
                path: 'comment',
                name: 'PostDetails-Comment',
                component: () => import('../views/PostDetails-Comment.vue'),
                meta: {requiresAuth: true }
            }
        ]
    },
    {/*发帖*/
        path: '/toPost',
        name: 'ToPost',
        component: () => import('@/views/ToPost.vue'),
        //showTabBar: false 设置为 false 不显示底部导航栏
        //requiresAuth: true 设置为 true 表示需要登录才能访问
        meta: { showTabBar: false, requiresAuth: true }
    },
    {/*home的帖子详情*/
        path: '/post/:id',
        name: 'PostSee',
        component:() => import('@/views/PostSee.vue'),
        meta: {requiresAuth: true }
    },
    {/*个人*/
        path: '/profile',
        name: 'Profile',
        component:()=>import('../views/Profile.vue'),
        meta: {requiresAuth: true }
    },
    {//关注
        path:'/follows/:id',
        name:'follows',
        component:()=>import('../views/follows.vue'),
        meta: {requiresAuth: true }
    },
    {//粉丝
        path:'/follows/:id',
        name:'follows',
        component:()=>import('../views/follows.vue'),
        meta: {requiresAuth: true }
    },
    {//收藏
        path:'/collections/:id',
        name:'collections',
        component:()=>import('../views/collections.vue'),
        meta: {requiresAuth: true }
    },
    {//历史
        path:'/history/:id',
        name:'history',
        component:()=>import('../views/history.vue'),
        meta: {requiresAuth: true }
    },
    {//其他用户详情展示
        path:'/user/:userId',
        name:'UserDetail',
        component:()=>import('../views/UserDetail.vue'),
        meta: { showTabBar: false } // 设置为 false 不显示底部导航栏
    },
    {//游戏库
        path: '/gameLibrary',
        name: 'GameLibrary',
        component:() => import('@/views/GameLibrary.vue'),
        redirect: '/gameLibrary/recommend',
        children: [
            {
                path: 'recommend',
                name: 'GameLibraryRecommend',
                component:() => import('../views/GameLibraryRecommend.vue')
            },
            {
                path: 'rank',
                name: 'GameLibraryRank',
                component:() => import('../views/GameLibraryRank.vue')
            },
        ]
    },
    {//游戏库详情页
        path: '/goGameDetail/:id',
        name: 'goGameDetail',
        component: () => import('@/views/GameLibraryDetails.vue')
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 全局守卫：检查是否需要登录
router.beforeEach(async (to, from, next) => {
    console.log("全局守卫启动")
    if (to.matched.some(record => record.meta.requiresAuth)) {
        const token = localStorage.getItem('token');
        if (!token) {
            next({ path: '/login', query: { redirect: to.fullPath } });
        } else {
            try {

                // 向后端发送 token 验证请求
                const response = await axios.get('/api/users/check', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                if (response.code === 200) {
                    next(); // token 有效，放行
                } else {
                    localStorage.removeItem('token');
                    next('/login'); // token 无效，跳转登录
                }
            } catch (error) {
                localStorage.removeItem('token');
                next('/login'); // 请求失败，跳转登录
            }
        }
    } else {
        next(); // 不需要认证的路由
    }
});

export default router;